function geneCMEfile(statName,OptsGen)
%geneCMEfile - Generation of a file for CME external analysis
%
%   geneCMEfile(statName,OptsGen)
%
% This function generates a .txt file for CME evaluation and mitigation
% by means of an external MATLAB toolbox (in particular, GNSS_TS_NRS, 
% described in He, X., Yu, K., Montillet, J.-P., Xiong, C., Lu, T., 
% Zhou, S., Ma, X., Cui, H., Ming, F., 2020. GNSS-TS-NRS: An Open-Source 
% MATLAB-Based GNSS Time Series Noise Reduction Software. Remote Sensing, 
% 12, 3532. https://doi.org/10.3390/rs12213532).
% This file, related to the station statName (4-letters name), generated
% by means of data on the correspoding tsData file in the folder defined
% in OptsGen and placed in the folder also identified by OptsGen, is
% arranged in this way for each row:
% 
%  statName datefrac E N V sE SN sV cEN cEV cNV lon lat
% 
% where datefrac is the date in year fraction form (e.g. 2022.8630 for
% November 11, 2022), E (N, V) is the East (North, Vectical) coordinate,
% sE (sN, sV) is the standard deviation of E (N, V),   

filenaOut = 'cacchio.txt';


if nargin < 2
    OptsGen = [];
end
if isempty(OptsGen)
    [filyg,pathyg] = uigetfile(...
        {'*.mat','(*.mat)'},...
        'STAVEL OPTIONS FILE (*.mat)');
    if isnumeric(filyg) || isnumeric(pathyg)
        filenag = []; 
    else
        filenag = fullfile(pathyg,filyg);
        try 
            S = load(fielnag);
            if isfield(S,'Opts') 
                OptsGen = S.Opts;
            elseif isfield(S,'OptsGen')
                OptsGen = S.OptsGen;
            else
                filenag = [];
            end
        catch
            filenag = [];
        end
    end
    if isempty(filenag)
        return
    end
end


filenats = fullfile(OptsGen.dirTs,[statName OptsGen.AddTs '.mat']);
[ts,IT] = tsDataFileIn(filenats);
if ~IT
    return
end

dateyfrac = ts.dateyfrac;
numrow = numel(dateyfrac);
Ed = ts.Ed;              
Nd = ts.Nd;              
Vd = ts.Vd;             
sE = ts.sE;              
sN = ts.sN;              
sV = ts.sV;              
cEN = ts.cEN;             
cEV = ts.cEV;            
cNV = ts.cNV;             
Lat = ts.Lat;            
Lon = ts.Lon;

Cf = cell(numrow,13);

for k = 1:numrow
    Cf(k,1) = {statName};
    Cf(k,2) = {dateyfrac(k)};
    Cf(k,3) = {Ed(k)};
    Cf(k,4) = {Nd(k)};
    Cf(k,5) = {Vd(k)};
    Cf(k,6) = {sE(k)};
    Cf(k,7) = {sN(k)};
    Cf(k,8) = {sV(k)};
    Cf(k,9) = {cEN(k)};
    Cf(k,10) = {cEV(k)};
    Cf(k,11) = {cNV(k)};
    Cf(k,12) = {Lon(k)};
    Cf(k,13) = {Lat(k)};
end

writecell(Cf,filenaOut,'delimiter','\t');